/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package Client;

import java.io.FileInputStream;
import java.io.IOException;
import java.rmi.RemoteException;
import javax.swing.JFileChooser;
import Shared.*;
import java.io.BufferedInputStream;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;

import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.nio.charset.Charset;

import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;


/**
 *
 * + * @author shimaa
 */
public class ChatWonePerson extends javax.swing.JFrame {
    private ClientInt reciverClient;//remote obj of reciever
    private ClientImp clientImp;
    private String ident;
    ArrayList<User> friendArray = new ArrayList<>();
    int sendFlag;
    
    public ChatWonePerson(ClientInt cli,String ident,User meUser,User friendUser) {
        try {
            
            clientImp = new ClientImp();
        } catch (RemoteException ex) {
            Logger.getLogger(ChatWonePerson.class.getName()).log(Level.SEVERE, null, ex);
        }
        reciverClient=cli;
        this.ident=ident;
        friendArray.add(0,meUser);
        friendArray.add(1,friendUser);
        int index = ident.indexOf(":");
        String sender = ident.substring(0, index);
        String  reciever= ident.substring(index + 1, ident.length());
        System.out.println("me:"+friendArray.get(0).getUserMail());
        System.out.println("friend:"+friendArray.get(1).getUserMail());
        System.out.println(sender+reciever);
        initComponents();
        counter.setVisible(false);
        this.setTitle(friendArray.get(1).getUserMail());        
        friendname.setText(friendArray.get(1).getUserName());
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
    }
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jPanel2 = new javax.swing.JPanel();
        jPanel3 = new javax.swing.JPanel();
        jPanel5 = new javax.swing.JPanel();
        text = new javax.swing.JTextField();
        interactive = new javax.swing.JTextField();
        jPanel4 = new javax.swing.JPanel();
        jButton2 = new javax.swing.JButton();
        jButton1 = new javax.swing.JButton();
        msgarea = new javax.swing.JScrollPane();
        MsgArea = new javax.swing.JEditorPane();
        jPanel6 = new javax.swing.JPanel();
        friendname = new javax.swing.JLabel();
        counter = new javax.swing.JLabel();
        jMenuBar1 = new javax.swing.JMenuBar();
        filemenu = new javax.swing.JMenu();
        saveconv = new javax.swing.JMenuItem();
        history = new javax.swing.JMenuItem();
        exit = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Chat ");
        setPreferredSize(new java.awt.Dimension(414, 355));
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosed(java.awt.event.WindowEvent evt) {
                formWindowClosed(evt);
            }
        });

        jPanel1.setBackground(new java.awt.Color(212, 197, 229));
        jPanel1.setLayout(new java.awt.BorderLayout());

        jPanel2.setBackground(new java.awt.Color(212, 197, 229));
        jPanel2.setLayout(new java.awt.BorderLayout());

        jPanel3.setBackground(new java.awt.Color(102, 5, 51));
        jPanel3.setLayout(new java.awt.BorderLayout());

        jPanel5.setBackground(new java.awt.Color(102, 5, 51));
        jPanel5.setLayout(new java.awt.BorderLayout());

        text.setFont(new java.awt.Font("DejaVu Sans Condensed", 1, 14)); // NOI18N
        text.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                textActionPerformed(evt);
            }
        });
        text.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                textKeyTyped(evt);
            }
        });
        jPanel5.add(text, java.awt.BorderLayout.CENTER);

        interactive.setEditable(false);
        interactive.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                interactiveKeyTyped(evt);
            }
        });
        jPanel5.add(interactive, java.awt.BorderLayout.PAGE_START);

        jPanel4.setBackground(new java.awt.Color(102, 5, 51));

        jButton2.setBackground(new java.awt.Color(255, 255, 255));
        jButton2.setFont(new java.awt.Font("DejaVu Serif Condensed", 1, 14)); // NOI18N
        jButton2.setForeground(new java.awt.Color(102, 5, 51));
        jButton2.setText("Attach");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });
        jPanel4.add(jButton2);

        jButton1.setBackground(new java.awt.Color(255, 255, 255));
        jButton1.setFont(new java.awt.Font("DejaVu Serif Condensed", 1, 14)); // NOI18N
        jButton1.setForeground(new java.awt.Color(102, 5, 51));
        jButton1.setText("Send");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
        jPanel4.add(jButton1);

        jPanel5.add(jPanel4, java.awt.BorderLayout.LINE_START);

        jPanel3.add(jPanel5, java.awt.BorderLayout.CENTER);

        jPanel2.add(jPanel3, java.awt.BorderLayout.PAGE_END);

        msgarea.setBackground(new java.awt.Color(212, 197, 229));

        MsgArea.setEditable(false);
        MsgArea.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(102, 5, 51)));
        MsgArea.setFont(new java.awt.Font("DejaVu Sans Condensed", 1, 14)); // NOI18N
        msgarea.setViewportView(MsgArea);

        jPanel2.add(msgarea, java.awt.BorderLayout.CENTER);

        jPanel6.setBackground(new java.awt.Color(102, 5, 51));

        friendname.setFont(new java.awt.Font("DejaVu Serif Condensed", 1, 13)); // NOI18N
        friendname.setForeground(new java.awt.Color(255, 255, 255));
        friendname.setText("friendname");

        counter.setForeground(new java.awt.Color(255, 255, 255));
        counter.setText("jLabel1");

        javax.swing.GroupLayout jPanel6Layout = new javax.swing.GroupLayout(jPanel6);
        jPanel6.setLayout(jPanel6Layout);
        jPanel6Layout.setHorizontalGroup(
            jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel6Layout.createSequentialGroup()
                .addGap(22, 22, 22)
                .addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(counter)
                    .addComponent(friendname))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel6Layout.setVerticalGroup(
            jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel6Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(friendname)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 204, Short.MAX_VALUE)
                .addComponent(counter)
                .addContainerGap())
        );

        jPanel2.add(jPanel6, java.awt.BorderLayout.LINE_START);

        jPanel1.add(jPanel2, java.awt.BorderLayout.CENTER);

        filemenu.setForeground(new java.awt.Color(255, 255, 255));
        filemenu.setText("File");
        filemenu.setFont(new java.awt.Font("DejaVu Serif Condensed", 1, 13)); // NOI18N

        saveconv.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.CTRL_MASK));
        saveconv.setFont(new java.awt.Font("DejaVu Serif Condensed", 1, 13)); // NOI18N
        saveconv.setForeground(new java.awt.Color(102, 5, 51));
        saveconv.setMnemonic('S');
        saveconv.setText("Save Conversation");
        saveconv.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                saveconvActionPerformed(evt);
            }
        });
        filemenu.add(saveconv);

        history.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_H, java.awt.event.InputEvent.CTRL_MASK));
        history.setFont(new java.awt.Font("DejaVu Serif Condensed", 1, 13)); // NOI18N
        history.setForeground(new java.awt.Color(102, 5, 51));
        history.setMnemonic('H');
        history.setText("Load History");
        history.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                historyActionPerformed(evt);
            }
        });
        filemenu.add(history);

        exit.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_E, java.awt.event.InputEvent.CTRL_MASK));
        exit.setFont(new java.awt.Font("DejaVu Serif Condensed", 1, 13)); // NOI18N
        exit.setForeground(new java.awt.Color(102, 5, 52));
        exit.setMnemonic('E');
        exit.setText("Exit Conversation");
        exit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                exitActionPerformed(evt);
            }
        });
        filemenu.add(exit);

        jMenuBar1.add(filemenu);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed

        Thread thread = new Thread(new Runnable() {
            public void run() {
                ChatWonePerson t = ChatWonePerson.this;
                JFileChooser fc = new JFileChooser();
                if (fc.showOpenDialog(t)
                        == JFileChooser.APPROVE_OPTION) {
                    String path = fc.getSelectedFile().getPath();
                    String name = fc.getSelectedFile().getName();

                    FileInputStream fis = null;
                    try {
                        fis = new FileInputStream(path);
                        BufferedInputStream in =new BufferedInputStream(fis);
                        
                         byte[] buf = new byte[1024];
                      reciverClient.reciveFilename(name);
                      counter.setText("ready to send file");
                    counter.setVisible(true);

                      while(in.read(buf)!=-1){
                          counter.setText("sending..");
                         reciverClient.reciveFile(buf);
                      }
                      if(in.read(buf)==-1){
                  reciverClient.reciveFileend();
                   counter.setVisible(false);
                 JOptionPane.showMessageDialog(null, "file is sent successfully","Finished",JOptionPane.OK_OPTION);

             
                      
                      }
                      in.close();
                                            //   counter.setVisible(false);

                    } catch (FileNotFoundException ex) {
                        Logger.getLogger(ChatWonePerson.class.getName()).log(Level.SEVERE, null, ex);
                        //  Logger.getLogger(genJpeg.class.getName()).log(Level.SEVERE, null, ex);
                    } catch (IOException ex) {
                        Logger.getLogger(ChatWonePerson.class.getName()).log(Level.SEVERE, null, ex);
                    } finally {
                        try {
                            fis.close();
                        } catch (IOException ex) {
                            Logger.getLogger(ChatWonePerson.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }

                }
            }
        });

        thread.start();
    }//GEN-LAST:event_jButton2ActionPerformed

    private void saveconvActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveconvActionPerformed

        JFileChooser fc = new JFileChooser();
        if (fc.showSaveDialog(ChatWonePerson.this) == JFileChooser.APPROVE_OPTION) //if the user selects a file
        {
            
            String path = fc.getSelectedFile().getPath();//get selected file and the path of the file
            File file = new File(path);
            String h = MsgArea.getText();
            try {
              
                FileOutputStream filewrite = new FileOutputStream(file,true);
		byte[] arr = h.getBytes();
		filewrite.write(arr);
		filewrite.close();
                
            } catch (FileNotFoundException ex) {
                Logger.getLogger(ChatWonePerson.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                Logger.getLogger(ChatWonePerson.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }//GEN-LAST:event_saveconvActionPerformed

    private void historyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_historyActionPerformed
        JFileChooser fc = new JFileChooser();
        if(fc.showOpenDialog(ChatWonePerson.this) == JFileChooser.APPROVE_OPTION) //if the user selects a file
        {
            String path = fc.getSelectedFile().getPath();//get selected file and the path of the file
            //ta.setText(path);
            try{
                FileInputStream fileread = new FileInputStream(path);  //read from the file 
                int size = fileread.available();  //select the available size (since I want to read the whole fiel..so I use available) 									//and return i'ts size
                System.out.println(size);
                byte[] arr= new byte[size];   //Then put the size in an array of bytes
                fileread.read(arr);    //Then read the lines from the file
                MsgArea.setText(new String(arr));     //Then print the file in the textarea..but convert the bytes into string first
                fileread.close();       //close the stream
            }
            catch(IOException ex)
            {
                ex.printStackTrace();
            }
        }
        if (fc.showOpenDialog(ChatWonePerson.this) == JFileChooser.APPROVE_OPTION) //if the user selects a file
        {
            String path = fc.getSelectedFile().getPath();//get selected file and the path of the file

            try {
                FileInputStream fileread = new FileInputStream(path);  //read from the file 
                int size = fileread.available();  //select the available size (since I want to read the whole fiel..so I use available) 	
                byte[] arr = new byte[size];   //Then put the size in an array of bytes
                fileread.read(arr);
                //new History(new String(arr));
                fileread.close();       //close the stream
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }//GEN-LAST:event_historyActionPerformed

    private void exitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exitActionPerformed
        dispose();
    }//GEN-LAST:event_exitActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed

        if (text.getText() !=null) {
            sendFlag = 1;
            try {            
                reciverClient.recieveMessage(friendArray.get(0).getUserName()+":"+text.getText(),ident,friendArray.get(0), friendArray.get(1));
            } catch (RemoteException ex) {
               
            }
            MsgArea.setText(MsgArea.getText() +friendArray.get(0).getUserName()+":"+text.getText() + '\n');
            text.setText("");
            interactive.setText("");
        }
    }//GEN-LAST:event_jButton1ActionPerformed

    private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed

        clientImp.removeChatOpen(ident);
    }//GEN-LAST:event_formWindowClosed

    private void jTextField1FocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextField1FocusGained

//        clientint=client.startChatWithFriend(reciever);

    }//GEN-LAST:event_jTextField1FocusGained

    private void textActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_textActionPerformed
        // TODO add your handling code here:
        if (text.getText() !=null) {
            try {            
                reciverClient.recieveMessage(friendArray.get(0).getUserName()+":"+text.getText(),ident,friendArray.get(0), friendArray.get(1));
            } catch (RemoteException ex) {
                Logger.getLogger(ChatWonePerson.class.getName()).log(Level.SEVERE, null, ex);
            }
            MsgArea.setText(MsgArea.getText() +friendArray.get(0).getUserName()+":"+text.getText() + '\n');
            text.setText("");
        }
    }//GEN-LAST:event_textActionPerformed

    private void interactiveKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_interactiveKeyTyped
        // TODO add your handling code here
    }//GEN-LAST:event_interactiveKeyTyped

    private void textKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_textKeyTyped
        // TODO add your handling code here:
        if(sendFlag == 1)
        {
            try {            
                    reciverClient.interactiveMessage(friendArray.get(0).getUserName()+":"+text.getText(),ident,friendArray.get(0), friendArray.get(1));
                } catch (RemoteException ex) {
                    Logger.getLogger(ChatWonePerson.class.getName()).log(Level.SEVERE, null, ex);
                }
        }
        //interactive.setText(friendArray.get(0).getUserName()+":"+text.getText());
    }//GEN-LAST:event_textKeyTyped
    
    public void receiveMessageInTextArea(String msg) {
        MsgArea.setText(MsgArea.getText() +msg+'\n');
    }
    public void interactiveMessageInTextField(String msg) {
        interactive.setText(msg);
    }


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JEditorPane MsgArea;
    private javax.swing.JLabel counter;
    private javax.swing.JMenuItem exit;
    private javax.swing.JMenu filemenu;
    private javax.swing.JLabel friendname;
    private javax.swing.JMenuItem history;
    private javax.swing.JTextField interactive;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JPanel jPanel6;
    private javax.swing.JScrollPane msgarea;
    private javax.swing.JMenuItem saveconv;
    private javax.swing.JTextField text;
    // End of variables declaration//GEN-END:variables
}
